package com.zdp.nio.channel.filechannel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Objects;

public class FileChannelCopyTest {
    public static void main(String[] args) throws IOException{
        String sourceFileName = "D:\\code\\basic-code\\netty-test\\src\\main\\resources\\File.txt";
        String targetFileName = "D:\\code\\basic-code\\netty-test\\src\\main\\resources\\NewFile.txt";
        copy(sourceFileName,targetFileName);
    }


    public static void copy(String sourceFileName, String targetFileName) throws IOException {
        File sourceFile = new File(sourceFileName);
        File targetFile = new File(targetFileName);
        // 若文件不存在，则创建一个新的文件
        if (!targetFile.exists()) {
            targetFile.createNewFile();
        }
        long startTime = System.currentTimeMillis();
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        FileChannel sourceChannel = null;
        FileChannel targetChannel = null;
        try {
            inputStream = new FileInputStream(sourceFile);
            outputStream = new FileOutputStream(targetFile);
            sourceChannel = inputStream.getChannel();
            targetChannel = outputStream.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int readLength = -1;
            while ((readLength = sourceChannel.read(byteBuffer)) != -1) {
                System.out.println("> 读取 : " + readLength + " 个字节");
                // 切换 buffer模式
                byteBuffer.flip();
                int writeLength = 0;
                // 写入文件
                while ((writeLength = targetChannel.write(byteBuffer)) != 0) {
                    System.out.println("> 写入 : " + writeLength + " 个字节");
                }
                // 切换到写模式
                byteBuffer.clear();
                // 强制写盘
                targetChannel.force(true);
            }
        } finally {
            long endTime = System.currentTimeMillis();
            System.out.println("复制花费时间 ： " + (endTime - startTime));
            if(Objects.nonNull(inputStream)){
                inputStream.close();
            }
            if(Objects.nonNull(outputStream)){
                outputStream.close();
            }
            if(Objects.nonNull(sourceChannel)){
                sourceChannel.close();
            }
            if(Objects.nonNull(targetChannel)){
                targetChannel.close();
            }
        }

    }

}
